package com.cnswhy.cloud.server.app.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.utils.CnswhyUtil;
import com.cnswhy.cloud.common.logging.uitls.MDCUtil;
import com.cnswhy.cloud.common.rabbitmq.service.MessageService;
import com.cnswhy.cloud.common.redis.annotation.RedisLock;
import com.cnswhy.cloud.common.redis.model.LockTimeoutStrategy;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.app.annotation.NotDuplicate;
import com.cnswhy.cloud.server.app.utils.MessageSendUtils;
import com.cnswhy.cloud.server.app.utils.RSAUtils;
import com.cnswhy.cloud.server.common.entity.constant.AmqpExchange;
import com.cnswhy.cloud.server.common.entity.enumeration.OemCode;
import com.cnswhy.cloud.server.common.entity.enumeration.SmsType;
import com.cnswhy.cloud.server.common.entity.mq.RegisterMsg;
import com.cnswhy.cloud.server.common.entity.mq.SmsSendMQ;
import com.cnswhy.cloud.server.common.entity.mq.SyncIpMsg;
import com.cnswhy.cloud.server.core.constant.RedisConstant;
import com.cnswhy.cloud.server.core.dto.CustomerModifyPasswordDto;
import com.cnswhy.cloud.server.core.dto.CustomerRegistDto;
import com.cnswhy.cloud.server.core.entity.*;
import com.cnswhy.cloud.server.core.oem.OemService;
import com.cnswhy.cloud.server.core.query.QueryGenerator;
import com.cnswhy.cloud.server.core.service.CustomerWechatService;
import com.cnswhy.cloud.server.core.service.SysConfigService;
import com.cnswhy.cloud.server.core.service.app.AppMenuService;
import com.cnswhy.cloud.server.core.service.app.NoticeService;
import com.cnswhy.cloud.server.core.service.app.SlideshowService;
import com.cnswhy.cloud.server.core.service.customer.CustomerService;
import com.cnswhy.cloud.server.core.utils.PasswordCoder;
import com.cnswhy.cloud.server.core.vo.RespVo;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main")
@Api(tags = "登录注册控制层")
@Slf4j
public class LoginController {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SlideshowService slideshowService;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private AppMenuService appMenuService;

    @Autowired
    MessageService messageService;
    @Autowired
    OemService oemService;
    @Autowired
    private CustomerWechatService customerWechatService;


    /**
     * 账号密码登录
     *
     * @param loginName
     * @param password
     * @param request
     * @return
     */
    @ApiOperation(value = "登录方法", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginName", value = "手机号", required = true),
            @ApiImplicitParam(name = "loginType", value = "登录类型(1:账号密码登录 2:微信登录)", required = false),
            @ApiImplicitParam(name = "openId", value = "openId(loginType =  2 必填)", required = false),
            @ApiImplicitParam(name = "password", value = "密码", required = true)})
    @RequestMapping("/doLogin")
    @ResponseBody
    public RespVo doLogin(String loginName, String password, String loginType, String openId, HttpServletRequest request) {

        if (StringUtils.isBlank(loginType)) {
            loginType = "1";
        }
        RespVo vo = new RespVo();
        if (loginType.equals("1")) {

            log.info("登录方法:{} {}", loginName, password);
            if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(password)) {
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("用户名和密码不能为空!");
                return vo;
            }
            Customer customer = customerService.queryByLoginName(loginName);
            if (customer == null) {
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("用户不存在!");
                return vo;
            }
            if (customer.getStatus().intValue() == 1) {
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("用户已禁用!");
                return vo;
            }

            String pwd = null;
            try {
                pwd = RSAUtils.decryptString(password);//解密
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!(PasswordCoder.validatePassword(customer.getPassWord(), pwd))) {
                vo.setCode(RespVo.VALIDATE_ERROR);
                vo.setMessage("密码错误");
                return vo;
            }

            redisService.hset(RedisConstant.CUSTOMER_SESSION_KEY, request.getSession().getId(), customer);
            //单机登录，在过滤器中判断
            redisService.hset(RedisConstant.CUSTOMER_SESSION_ID, String.valueOf(customer.getId()), request.getSession().getId());

            customer.setPassWord("");
            vo.setMessage("登录成功");
            vo.setResult(request.getSession().getId());
            String ip = CnswhyUtil.getHttpServletRequestIpAddress();
            if(StringUtils.isNotBlank(ip)){
                SyncIpMsg syncIpMsg = SyncIpMsg.builder().customerId(customer.getId()).loginIp(ip).build();
                messageService.sendQueueByObject(AmqpExchange.SYNC_LOGIN_IP_MESSAGE, syncIpMsg);
                //IPinfoResponse iPinfoResponse = aliyunIpService.getIPinfo(ip);
                //log.info("登录IP：{}, 地址信息{}", ip, iPinfoResponse.toString() );
            }
            return vo;

        } else if (loginType.equals("2")) {
            //微信登录  先判断库中有无openId
            if (StringUtils.isBlank(openId)) {
                vo.setMessage("openId为空");
                vo.setCode(RespVo.VALIDATE_ERROR);
                return vo;
            }

            List<CustomerWechat> queryPage = customerWechatService.list(Wraps.<CustomerWechat>lbQ().eq(CustomerWechat::getOpenId, openId));
            if (queryPage.size() == 1) {
                Customer customer = customerService.queryById(queryPage.get(0).getCustomerId());
                if (customer == null) {
                    vo.setCode(RespVo.CODE_ERROR);
                    vo.setMessage("用户不存在!");
                    return vo;
                }
                redisService.hset(RedisConstant.CUSTOMER_SESSION_KEY, request.getSession().getId(), customer);
                //单机登录，在过滤器中判断
                redisService.hset(RedisConstant.CUSTOMER_SESSION_ID, String.valueOf(customer.getId()), request.getSession().getId());
                vo.setMessage("登录成功");
                vo.setResult(request.getSession().getId());
                return vo;
            } else {
                vo.setMessage("首次授权，请绑定手机号");
                vo.setCode(RespVo.CODE_OTHER);
                return vo;
            }

        } else {
            vo.setMessage("登录类型错误");
            vo.setCode(RespVo.VALIDATE_ERROR);
            return vo;
        }
    }
    /**
     * 账号密码登录
     *
     * @param loginName
     * @param password
     * @param request
     * @return
     */
    @ApiOperation(value = "登录方法(不加密)", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginName", value = "手机号", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)})
    @RequestMapping("/login")
    @ResponseBody
    public RespVo login(String loginName, String password, HttpServletRequest request) {
        RespVo vo = new RespVo();
        log.info("登录方法:{} {}", loginName, password);
        if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(password)) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("用户名和密码不能为空!");
            return vo;
        }
        Customer customer = customerService.queryByLoginName(loginName);
        if (customer == null) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("用户不存在!");
            return vo;
        }
        if (customer.getStatus().intValue() == 1) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("用户已禁用!");
            return vo;
        }

        /*String pwd = null;
        try {
            pwd = RSAUtils.decryptString(password);//解密
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        if (!(PasswordCoder.validatePassword(customer.getPassWord(), password))) {
            vo.setCode(RespVo.VALIDATE_ERROR);
            vo.setMessage("密码错误");
            return vo;
        }

        redisService.hset(RedisConstant.CUSTOMER_SESSION_KEY, request.getSession().getId(), customer);
        //单机登录，在过滤器中判断
        redisService.hset(RedisConstant.CUSTOMER_SESSION_ID, String.valueOf(customer.getId()), request.getSession().getId());

        customer.setPassWord("");
        vo.setMessage("登录成功");
        vo.setResult(request.getSession().getId());
        String ip = CnswhyUtil.getHttpServletRequestIpAddress();
        if(StringUtils.isNotBlank(ip)){
            SyncIpMsg syncIpMsg = SyncIpMsg.builder().customerId(customer.getId()).loginIp(ip).build();
            messageService.sendQueueByObject(AmqpExchange.SYNC_LOGIN_IP_MESSAGE, syncIpMsg);
            //IPinfoResponse iPinfoResponse = aliyunIpService.getIPinfo(ip);
            //log.info("登录IP：{}, 地址信息{}", ip, iPinfoResponse.toString() );
        }
        return vo;
    }

    /**
     * 获取加密秘钥
     *
     * @param request
     * @return
     */
    @GetMapping("/loginData")
    @ResponseBody
    @ApiOperation(value = "获取加密秘钥", httpMethod = "GET")
    public RespVo loginData(HttpServletRequest request) {
        log.info("获取加密秘钥");

        RespVo response = new RespVo();
        try {
            /*RSAPublicKey rsap = (RSAPublicKey) RSAUtils.generateKeyPair(redisService).getPublic();
            String modulus = rsap.getModulus().toString(16);
            String exponent = rsap.getPublicExponent().toString(16);*/

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("modulus", "d08800b143eef6c85db3dbcbd38acf0ab287a5fd1cf45a5a998d5cbaf92fe419b2c72d8ee09b30be45115d03f52e151b0ec5ade7a5b08b7f9b1af91072d6f7b3af4274783325c19fafe8294a0032e0bf7a7be1587147c3a77967e761904c609c35a42a5824e54ac535aa64a2b45d1208a7d3ad8a9ea4ed266ed2689dfb5c0b83");
            map.put("exponent", "10001");
            map.put("isChaoRenHaiGou", oemService.isChaoRenGou());
            map.put("imgPrefix", String.valueOf(redisService.hget(RedisConstant.SYS_CONFIG_1, RedisConstant.FTP_PATH_PREFIX)));
            map.put("imgPrefix", "");
            response.setResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("加载密钥异常，rsa错误");
        }
        return response;
    }

    @PostMapping("/getVerifyCode")
    @ResponseBody
    @ApiOperation(value = "获取注册验证码", httpMethod = "POST")
    @ApiParam(name = "mobile", value = "手机号码", required = true)
    public RespVo getVerifyCode(String mobile, HttpServletRequest request) {
        log.info("获取注册验证码:{}", mobile);

        RespVo respVo = new RespVo();
        try {
            // 手机号码校验
            if (StringUtils.isBlank(mobile)) {
                // 手机号是否为空
                respVo.setCode(RespVo.VALIDATE_ERROR);
                respVo.setMessage("请输入手机号码");
                return respVo;
            }
            if (mobile.length() != 11) {
                // 手机号长度
                respVo.setCode(RespVo.VALIDATE_ERROR);
                respVo.setMessage("手机号长度不对:" + mobile);
                return respVo;
            }
            Customer queryByLoginName = customerService.queryByLoginName(mobile);
            if (queryByLoginName != null) {
                respVo.setCode(RespVo.CODE_ERROR);
                respVo.setMessage("手机号码已经被注册");
                return respVo;
            }
            // 生成验证码
            String verifyCode = MessageSendUtils.generateSecureCode(4);
//            String content = "您的验证码为：" + verifyCode + "，10分钟内有效。验证码提供给他人可能导致账号被盗，请勿泄露，谨防被骗。";
            /*Map<String, Object> map = new HashMap<String, Object>();
            map.put("code", verifyCode);
            SendSmsUtil.sendSms(mobile, "SMS_200310059", JSON.toJSONString(map));*/
            SmsSendMQ smsSendMQ = SmsSendMQ.builder()
                    .content(null)
                    .mobile(mobile)
                    .smsType(SmsType.SMS_CODE)
                    .verifyCode(verifyCode).build();
            smsSendMQ.setTraceId(MDCUtil.getTraceId());
            messageService.sendQueueByObject(AmqpExchange.SEND_MESSAGE, smsSendMQ);
            // 记录验证码
            String redisKey = RedisConstant.VERIFY_CODE_REDIS_KEY + mobile;
            redisService.set(redisKey, verifyCode);
            redisService.expire(redisKey, 600L);

            // 返回结果
            respVo.setCode(RespVo.CODE_SUCCESS);
            respVo.setMessage("获取验证码成功");
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("获取验证码失败");
            log.error("获取验证码异常：", e);
        }
        return respVo;
    }

    @PostMapping("/getPasswordVerifyCode")
    @ResponseBody
    @ApiOperation(value = "获取忘记密码验证码", httpMethod = "POST")
    @ApiParam(name = "mobile", value = "手机号码", required = true)
    public RespVo getPasswordVerifyCode(String mobile, HttpServletRequest request) {
        log.info("获取忘记密码验证码:{}", mobile);
        RespVo respVo = new RespVo();
        try {
            // 手机号码校验
            if (StringUtils.isBlank(mobile)) {
                // 校验登录名是否被使用
                respVo.setCode(RespVo.VALIDATE_ERROR);
                respVo.setMessage("请输入手机号码");
                return respVo;
            }
            // 生成验证码
            String verifyCode = MessageSendUtils.generateSecureCode(4);
            SmsSendMQ smsSendMQ = SmsSendMQ.builder()
                    .content(null)
                    .mobile(mobile)
                    .smsType(SmsType.SMS_CODE)
                    .verifyCode(verifyCode).build();
            smsSendMQ.setTraceId(MDCUtil.getTraceId());
            messageService.sendQueueByObject(AmqpExchange.SEND_MESSAGE, smsSendMQ);

            // 记录验证码
            String redisKey = RedisConstant.PASS_VERIFY_CODE_REDIS_KEY + mobile;
            redisService.set(redisKey, verifyCode);
            redisService.expire(redisKey, 600L);

            // 返回结果
            respVo.setCode(RespVo.CODE_SUCCESS);
            respVo.setMessage("获取验证码成功");
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("获取验证码失败");
            log.error("获取验证码异常：", e);
        }
        return respVo;
    }


    /**
     * 描述：客户自主注册
     * 作者：张润泽
     * 时间：2018年7月18日 下午5:06:09
     *
     * @return
     */
    @ApiOperation(value = "注册方法", httpMethod = "POST")
    @ApiParam(name = "bo", value = "用户注册bo")
    @PostMapping("/regist")
    @ResponseBody
    @NotDuplicate
    public RespVo regist(CustomerRegistDto bo, HttpServletRequest request) {
        log.info("注册:{}", JSON.toJSONString(bo));

        RespVo respVo = new RespVo();
        try {
            //基本参数校验
            /*BeanValidation<CustomerRegistDto> validatResult = new BeanValidation<CustomerRegistDto>(bo);
            if (validatResult.hasError())
            {
                respVo.setCode(RespVo.VALIDATE_ERROR);
                respVo.setMessage(validatResult.getError());
                respVo.setResult(validatResult.getAllErrors());
                return respVo;
            }*/

            // 验证码校验
            if (!checkVerifyCode(bo.getMobile(), bo.getVerifyCode())) {
                respVo.setCode(RespVo.VALIDATE_ERROR);
                respVo.setMessage("验证码错误");
                return respVo;
            }

            // 手机号码校验
            Customer entity = new Customer();
            entity.setLoginName(bo.getMobile());
            Customer customer = customerService.queryByLoginName(bo.getMobile());
            if (customer != null) {
                respVo.setCode(RespVo.CODE_OTHER);
                respVo.setMessage("手机号码重复注册，请直接登录");
                return respVo;
            }

            Customer promoter = null;
            // 邀请人校验
            if (StringUtils.isNotBlank(bo.getPromoterMobile())) {
                promoter = customerService.queryByLoginName(bo.getPromoterMobile());
                if (promoter == null) {
                    respVo.setCode(RespVo.VALIDATE_ERROR);
                    respVo.setMessage("邀请人不存在");
                    return respVo;
                }

                // 设置邀请人id
                entity.setPromoterId(promoter.getId());
                entity.setPromoterMobile(promoter.getLoginName());
            }else{
                /*respVo.setCode(RespVo.VALIDATE_ERROR);
                respVo.setMessage("请联系推荐人分享注册");
                return respVo;*/
            }
            /*
            if (StringUtils.isBlank(bo.getPayPassword())) {
                respVo.setCode(RespVo.VALIDATE_ERROR);
                respVo.setMessage("交易密码为空");
                return respVo;
            }*/


            // 密码解密
            String password = null;
            String PayPassword = null;
            try {
                password = RSAUtils.decryptString(bo.getPassword());//解密
                PayPassword = RSAUtils.decryptString(bo.getPayPassword());//解密

            } catch (Exception e) {
                log.info("<== RSA解密，异常", e);
            }

            //设置密码
            entity.setPassWord(PasswordCoder.generatePassword(password));
            // 生成一个唯一的客户编号
            //状态初始化为正常
            entity.setStatus(2);//未激活
            entity.setCustomerType(0);
            entity.setIsSpell(1); //默认未参团
            entity.setTradePass(PasswordCoder.generatePassword(PayPassword));
            if(StringUtils.isBlank(entity.getOemCode())){
                entity.setOemCode(OemCode.WLYC.getVal());
            }
            entity.setContributionValue(1L);
            entity.setFirstPay(0);
            /*entity.setAvailableBalance(BigDecimal.ZERO);
            entity.setTotalProfit(BigDecimal.ZERO);
            entity.setContributionValue(BigDecimal.ZERO);
            entity.setCoupon(BigDecimal.ZERO);
            entity.setTotalCoupon(BigDecimal.ZERO);
            entity.setSpellValue(BigDecimal.ZERO);
            entity.setSpellBalance(BigDecimal.ZERO);
            entity.setContributionBalance(BigDecimal.ZERO);
            entity.setLoveBalance(BigDecimal.ZERO);*/
            customerService.save(entity);
            //更新PromoteList
            if(promoter != null){
                entity.setPromoterList(promoter.getPromoterList() + entity.getId());
                if(promoter.getPrimaryPromoterId() == null){
                    entity.setPrimaryPromoterId(promoter.getId());
                    entity.setPrimaryPromoterLevel(1L);
                    entity.setPrimaryPromoterPhone(promoter.getLoginName());
                }else{
                    entity.setPrimaryPromoterId(promoter.getPromoterId());
                    entity.setPrimaryPromoterLevel(promoter.getPrimaryPromoterLevel() + 1);
                    entity.setPrimaryPromoterPhone(promoter.getPrimaryPromoterPhone());
                }
            } else {
                entity.setPromoterList(entity.getId().toString());
                entity.setPrimaryPromoterLevel(0L);
            }
            customerService.updateById(entity);
            RegisterMsg registerMsg = RegisterMsg.builder().customerId(entity.getId())
                    .customerType(entity.getCustomerType())
                    .promoterMobile(entity.getPromoterMobile())
                    .loginName(entity.getLoginName())
                    .nickName(entity.getNickName())
                    .promoterId(entity.getPromoterId())
                    .realName(entity.getRealName()).build();
            registerMsg.setTraceId(MDCUtil.getTraceId());
            messageService.sendQueueByObject(AmqpExchange.REGISTER_MESSAGE, registerMsg);
            respVo.setCode(RespVo.CODE_SUCCESS);
            respVo.setMessage("注册成功");
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("注册失败");
            log.error("客户自主注册异常：", e);
        }
        return respVo;
    }

    @ApiOperation(value = "退出登录", httpMethod = "POST")
    @PostMapping("/loginOut")
    @ResponseBody
    public RespVo loginOut(HttpServletRequest request) throws Exception {
        log.info("退出登录");

        RespVo response = new RespVo();
        redisService.hdel(RedisConstant.CUSTOMER_SESSION_KEY, request.getSession().getId());
        response.setCode(RespVo.CODE_SUCCESS);
        response.setMessage("注销成功");
        response.setResult(null);
        return response;

    }

    /**
     * 修改密码
     *
     * @param bo
     * @param request
     * @return
     */
    @ApiOperation(value = "修改密码", httpMethod = "POST")
    @ApiParam(name = "bo", value = "修改密码对象")
    @PostMapping("/updatePass")
    @ResponseBody
    public RespVo updatePass(CustomerModifyPasswordDto bo, HttpServletRequest request) {
        log.info("修改密码:{}", JSON.toJSONString(bo));

        RespVo respVo = new RespVo();
        try {
            String redisVerifyCode = (String) redisService.get(RedisConstant.PASS_VERIFY_CODE_REDIS_KEY + bo.getMobile());
            if (StringUtils.isBlank(redisVerifyCode) || !StringUtils.equals(redisVerifyCode, bo.getVerifyCode())) {
                respVo.setCode(RespVo.VALIDATE_ERROR);
                respVo.setMessage("验证码错误");
                return respVo;
            }

            if (StringUtils.isBlank(bo.getPasswordType())) {
                bo.setPasswordType("1");
            }

            // 密码解密
            String newPassword = null;
            try {
                newPassword = RSAUtils.decryptString(bo.getNewPassword());//解密

            } catch (Exception e) {
                log.info("<== RSA解密，异常", e);
            }

            // 从数据库取出客户最新信息
            Customer entity = new Customer();
            entity.setLoginName(bo.getMobile());
            Customer customer = customerService.queryByLoginName(bo.getMobile());
            if (customer == null) {
                respVo.setCode(RespVo.CODE_ERROR);
                respVo.setMessage("账号不存在");
                return respVo;
            }

            entity.setId(customer.getId());
            /*if (bo.getPasswordType().equals("1")) {
                entity.setPassWord(PasswordCoder.generatePassword(newPassword));
            } else {
                entity.setTradePass(PasswordCoder.generatePassword(newPassword));
            }*/

            // 保存密码修改
            //customerService.updateById(entity);
            entity = updateCustomer(entity.getId(),bo.getPasswordType(),newPassword);

            respVo.setCode(RespVo.CODE_SUCCESS);
            respVo.setMessage("找回密码成功");
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("找回密码失败");
            log.error("找回密码异常：", e);
        }
        return respVo;
    }
    @RedisLock(name = "Customer", waitTime = 10,leaseTime = 60,keys = {"#id"},lockTimeoutStrategy = LockTimeoutStrategy.FAIL_FAST)
    private Customer updateCustomer(Long id,String type,String password){
        Customer customer = customerService.getById(id);
        if ("1".equals(type)) {
            customer.setPassWord(PasswordCoder.generatePassword(password));
        } else {
            customer.setTradePass(PasswordCoder.generatePassword(password));
        }
        customerService.updateById(customer);
        return customer;
    }

    @ApiOperation(value = "获取轮播图", httpMethod = "GET")
    @ApiParam(name = "type", value = "类型，0-为首页轮播图，1-首页banner，2-商城banner", required = true)
    @RequestMapping(value = "/ajaxSlidePage", method = RequestMethod.GET)
    @ResponseBody
    public RespVo ajaxSlidePage(HttpServletRequest request, Integer type) {
        log.info("获取轮播图:type:{}", type);
        RespVo respVo = new RespVo();
        try {
            List<Slideshow> pageList = slideshowService.list(Wraps.<Slideshow>lbQ().eq(Slideshow::getType, type).eq(Slideshow::getStatus, 0));
            respVo.setCode(RespVo.CODE_SUCCESS);
            respVo.setMessage("查询成功");
            respVo.setResult(pageList);
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("查询失败");
            log.error("查询轮播图列表异常：", e);
        }
        return respVo;
    }

    @RequestMapping(value = "/ajaxNoticePage", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取公告分页列表", httpMethod = "POST")
    @ApiParam(name = "bo", value = "公告bo")
    public RespVo ajaxNoticePage(Notice bo,
                                 @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) {
        log.info("获取公告分页列表:{},{},{}", JSON.toJSONString(bo), currentPage, pageSize);
        RespVo respVo = new RespVo();
        try {
            bo.setStatus(1);
            QueryWrapper<Notice> queryWrapper = QueryGenerator.initQueryWrapper(bo);
            queryWrapper.orderByDesc("create_date");
            Page<Notice> page = new Page<>(currentPage, pageSize);
            IPage<Notice> pageList = noticeService.page(page, queryWrapper);
            /*for (Notice notice : pageList.getRecords()) {
                notice.setContent(URLDecoder.decode(notice.getContent(), "UTF-8"));
                noticeService.updateById(notice);
            }*/
            respVo.setCode(RespVo.CODE_SUCCESS);
            respVo.setMessage("查询成功");
            respVo.setResult(pageList);
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("查询失败");
            log.error("查询公告列表异常：", e);
        }
        return respVo;
    }

    @ApiOperation(value = "获取首页APP菜单列表", httpMethod = "POST")
    @RequestMapping("/listAppMenu")
    @ResponseBody
    public RespVo listAppMenu() {
        log.info("获取首页APP菜单列表");

        RespVo vo = new RespVo();
        try {
            List<AppMenu> listAppMenu = appMenuService.list(Wraps.<AppMenu>lbQ().orderByAsc(AppMenu::getSortOrder));
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setMessage("查询成功");
            vo.setResult(listAppMenu);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询失败");
            log.error("查询失败", e);
        }
        return vo;
    }

    @Autowired
    SysConfigService sysConfigService;

    @ApiOperation(value = "根据传入版本号判断是否需要更新下载", httpMethod = "POST")
    @ApiParam(name = "currentVersion", value = "客户端当前版本", required = true)
    @RequestMapping("/querAppVersion")
    @ResponseBody
    public RespVo querAppVersion(String currentVersion) {
        log.info("根据传入版本号判断是否需要更新下载:{}", currentVersion);

        RespVo vo = new RespVo();

        try {
            SysConfig sysConfig = sysConfigService.getOne(Wraps.<SysConfig>lbQ().eq(SysConfig::getConfigKey, RedisConstant.ANDRIOD_APP_VERSION));
            log.error("========================当前版本号：" + currentVersion);
            log.error("========================版本号判断 ：" + StringUtils.equals(currentVersion, sysConfig.getConfigValue()));
            if (!StringUtils.equals(currentVersion, sysConfig.getConfigValue())) {
                SysConfig sysConfig1 = sysConfigService.getOne(Wraps.<SysConfig>lbQ().eq(SysConfig::getConfigKey, RedisConstant.ANDRIOD_APP_DOWNLOAD));
                vo.setResult(sysConfig1.getConfigValue());
            }
            vo.setCode(RespVo.CODE_SUCCESS);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询APP版本失败");
            log.error("判断版本失败", e);
        }
        return vo;
    }

    private boolean checkVerifyCode(String mobile, String verifyCode) {
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(verifyCode)) {
            return false;
        }

        String redisVerifyCode = (String) redisService.get(RedisConstant.VERIFY_CODE_REDIS_KEY + mobile);
        if (StringUtils.isBlank(redisVerifyCode) || !verifyCode.equals(redisVerifyCode)) {
            return false;
        }

        return true;
    }

    @ApiOperation(value = "获取客服微信", httpMethod = "POST")
    @RequestMapping("/getCusterSerUrl")
    @ResponseBody
    public RespVo getCusterSerUrl() {
        log.info("获取客服微信");

        RespVo vo = new RespVo();
        try {
            String custerSerUrl = (String) redisService.get(RedisConstant.CUSTOMER_SER_URL);
            if (StringUtils.isNotBlank(custerSerUrl)) {
                vo.setCode(RespVo.CODE_SUCCESS);
                vo.setMessage("查询成功");
                vo.setResult(custerSerUrl);
            } else {
                SysConfig sysConfig = sysConfigService.getOne(Wraps.<SysConfig>lbQ().eq(SysConfig::getConfigKey, "custerSer_url"));
                redisService.set(RedisConstant.CUSTOMER_SER_URL, sysConfig.getConfigValue(), 3600L);
                if (sysConfig != null) {
                    vo.setCode(RespVo.CODE_SUCCESS);
                    vo.setMessage("查询成功");
                    vo.setResult(sysConfig.getConfigValue());
                } else {
                    vo.setCode(RespVo.CODE_ERROR);
                    vo.setMessage("数据未配置");
                }
            }
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询失败");
            log.error("查询失败", e);
        }
        return vo;
    }

}
